﻿using Common.Infrastructure;
using CoreFtp;
using File.Api.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace File.Api.Utils
{
    public class FtpFileUtils
    {
        public static async Task UploadFileAsync(FileModel file, FtpFileParam param)
        {
            if (file.FileData == null || file.FileData.Length == 0)
            {
                return;
            }

            var newFileName = FileUtils.GetFileName(file.FileName);
            string dic = DateTime.Now.ToString("yyyy-MM-dd");

            using (var ftpClient = new FtpClient(new FtpClientConfiguration
            {
                Host = param.Host,
                Username = param.UserName,
                Password = param.Pasword,
                Port = param.Post
            }))
            {
                await ftpClient.LoginAsync();

                var s = await ftpClient.ListDirectoriesAsync();
                var temp = s.FirstOrDefault(t => t.Name == dic);
                if (temp == null)
                {
                    await ftpClient.CreateDirectoryAsync(dic);
                }

                await ftpClient.ChangeWorkingDirectoryAsync(dic);
                using (var writeStream = await ftpClient.OpenFileWriteStreamAsync(newFileName))
                {
                    await writeStream.WriteAsync(file.FileData, 0, file.FileData.Length);
                }
            }

            file.FilePath = string.Format(
                "ftp://{0}:{1}/{2}/{3}?username={4}&password={5}&host={0}&port={1}&directory={2}&name={3}",
                    param.Host,
                    param.Post,
                    dic, 
                    newFileName,
                    param.UserName, 
                    param.Pasword);
        }

        public static async Task DownloadFileAsync(DbFileModel file)
        {
            if (string.IsNullOrEmpty(file.FilePath))
            {
                return;
            }

            var path = file.FilePath;
            var param = path.Split('?')[1];
            var p = param.Split('&');
            Dictionary<string, string> dics = new Dictionary<string, string>();
            p.ForEach(t =>
            {
                dics[t.Split('=')[0]] = t.Split('=')[1];
            });
            var dic = dics["directory"];
            var filename = dics["name"];
            byte[] ret = null;
            using (var ftpClient = new FtpClient(new FtpClientConfiguration
            {
                Host = dics["host"],
                Username = dics["username"],
                Password = dics["password"],
                Port = LibSysUtils.ToInt(dics["port"])
            }))
            {
                await ftpClient.LoginAsync();
                await ftpClient.ChangeWorkingDirectoryAsync(dic);
                var length = await ftpClient.GetFileSizeAsync(filename);

                using (var readStream = await ftpClient.OpenFileReadStreamAsync(filename))
                {
                    ret = new byte[(int)length];
                    await readStream.ReadAsync(ret, 0, (int)length);
                }
            }

            file.FileData = ret;
        }
    }
}
